package com.s.rpc.handler;

import com.s.rpc.domain.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author ShenshenLuo
 * @email luoshenshen@buaa.edu.cn
 * @date 2025/5/11 14:49
 **/
public class RpcClientHandler extends SimpleChannelInboundHandler<Object> {

    @Setter
    @Getter
    private  Map<String, CompletableFuture<RpcResponse>> pendingRequests;

    public RpcClientHandler(Map<String, CompletableFuture<RpcResponse>> pendingRequests) {
        this.pendingRequests = pendingRequests;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("client received: ");
        RpcResponse response = (RpcResponse) msg;
        CompletableFuture<RpcResponse> future = pendingRequests.remove(response.getRequestId());
        if (future != null) {
            future.complete(response);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}
